package com.sunxboy.platform.application;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

class ServiceLoader<Service> {

    private static final String SERVICE_PREFIX = "META-INF/services/";
    private static final Logger LOG = Logger.getLogger(ServiceLoader.class);

    private final String resourceName;
    private final Class<Service> serviceType;

    private List<String> classes = null;

    public ServiceLoader(Class<Service> serviceType) {
        this.serviceType = serviceType;
        this.resourceName = SERVICE_PREFIX + serviceType.getName();
    }

    public Iterator<Service> iterator() {

        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classes == null) {
            readProviders(classLoader);
        }

        return new Iterator<Service>() {

            Iterator<String> classnames = classes.iterator();

            public boolean hasNext() {
                return classnames.hasNext();
            }

            public Service next() {
                String className = classnames.next();

                final Service instance;
                try {
                    Object object = Class.forName(className, true, classLoader).newInstance();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(String.format("Instantiated object of type: %s, toString() %s", object.getClass(), object));
                    }

                    instance = serviceType.cast(object);
                }
                catch (Exception e) {
                    throw new RuntimeException("Unable to instantiate specified service class", e);
                }
                return instance;
            }

            public void remove() {
                throw new UnsupportedOperationException("Not supported");
            }
        };
    }

    private void readProviders(ClassLoader classLoader) {
        classes = new LinkedList<String>();

        Enumeration<URL> resources;
        {
            try {
                resources = classLoader.getResources(this.resourceName);
            }
            catch (IOException e) {
                throw new RuntimeException("Unbale to load list of service providers", e);
            }
        }
        while (resources.hasMoreElements()) {
            URL resourceUrl = resources.nextElement();
            classes.addAll(readLine(resourceUrl));
        }

    }

    private List<String> readLine(URL resourceUrl) {
        List<String> resourceLines = new LinkedList<String>();
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = resourceUrl.openStream();
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);

            String line = "?";
            while ((line = bufferedReader.readLine()) != null) {
                if (line.trim().startsWith("#")) {
                    continue;
                }

                String className = line.trim();
                resourceLines.add(className);
            }
        }
        catch (Exception e) {
            throw new RuntimeException("Unable to load provider list", e);
        }
        finally {
            closeQuietly(bufferedReader);
            closeQuietly(inputStreamReader);
            closeQuietly(inputStream);

            bufferedReader = null;
            inputStreamReader = null;
            inputStream = null;
        }
        return resourceLines;
    }

    private void closeQuietly(InputStream input) {
        try {
            if (input != null) {
                input.close();
            }
        }
        catch (IOException ioe) {
            // ignore
        }
    }

    private void closeQuietly(Reader input) {
        try {
            if (input != null) {
                input.close();
            }
        }
        catch (IOException ioe) {
            // ignore
        }
    }

    public String getResourceName() {
        return resourceName;
    }

}
